package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.sky.constant.MessageConstant.*;
import static com.sky.entity.Orders.PENDING_PAYMENT;
import static com.sky.entity.Orders.UN_PAID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    private static final int ORDER_NUMBER_LENGTH = 12;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return OrderSubmitVO
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1. 处理地址和购物车异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook==null){
            //1.1 地址异常
            throw new AddressBookBusinessException(ADDRESS_BOOK_IS_NULL);
        }
        Long currentId = BaseContext.getCurrentId();
        List<ShoppingCart> list = shoppingCartMapper.getByUserId(currentId);
        if (list==null||list.size()==0){
            //1.2 购物车异常
            throw new ShoppingCartBusinessException(SHOPPING_CART_IS_NULL);
        }

        //2. 创建一条订单数据
        //2.1 拼接地址信息
        StringBuilder address=new StringBuilder();
        address.append(addressBook.getProvinceName())
                .append(addressBook.getCityName())
                .append(addressBook.getDistrictName())
                .append(addressBook.getDetail());
        //2.2 获取用户姓名
        User user = userMapper.getById(currentId);
        //2.3 填充订单信息【用时间戳作为订单号】
        String number = String.valueOf(System.currentTimeMillis());
        Orders orders = Orders.builder()
                .address(address.toString())
                .userName(user.getName())
                .orderTime(LocalDateTime.now())
                .number(number)
                .payStatus(UN_PAID)
                .status(PENDING_PAYMENT)
                .build();
        BeanUtil.copyProperties(ordersSubmitDTO,orders);
        BeanUtil.copyProperties(addressBook,orders);

        //3. 插入订单数据
        orderMapper.insert(orders);
        Long orderId = orders.getId();

        //4. 批量插入订单详情信息
        list.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            BeanUtil.copyProperties(shoppingCart,orderDetail);
            orderDetailMapper.insert(orderDetail);
        });


        //5. 清空购物车
        shoppingCartMapper.deleteByUserId(currentId);

        //6. 封装订单VO对象
        return OrderSubmitVO.builder()
                .id(orderId)
                .orderNumber(number)
                .orderAmount(ordersSubmitDTO.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }


    /**
     * 生成订单号
     * @return String
     */
    public String generateOrderNumber() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(ORDER_NUMBER_LENGTH);

        // 确保订单号的第一个数字不为0
        sb.append(random.nextInt(9) + 1);

        for (int i = 1; i < ORDER_NUMBER_LENGTH; i++) {
            sb.append(random.nextInt(10));
        }

        return sb.toString();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //通过WebSocket提醒商家接单
        Map<String, Object> map=new HashMap<>();
        map.put("type",1); //1.表示来单提醒  2.表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        orderMapper.update(orders);
    }


    /**
     * 客户催单
     * @param id
     */
    public void remind(Long id) {
        //1. 查询订单
        Orders order=orderMapper.getById(id);
        if (order==null){
            throw new OrderBusinessException(ORDER_STATUS_ERROR);
        }

        //2. 催单
        Map<String,Object> map=new HashMap<>();
        map.put("type",2); //1 来单提醒 2 客户催单
        map.put("orderId",id);
        map.put("content","订单为："+order.getNumber());
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
